<template>
  <div>
    <vxe-modal
      :title="modalTitle"
      v-model="show"
      :loading="loading"
      :mask="false"
      :lock-view="false"
      width="80vw"
      height="80vh"
      min-width="800px"
      destroy-on-close
      show-zoom
      remember
      resize
      show-footer
    >
      <!-- 主体部分： form 表单 -->
      <el-form
        ref="refForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息选项卡 -->
          <el-tab-pane
            :label="$t('menu.dev.action.tabs.base', '基本信息')"
            name="basic"
          >
            <BasicInfoForm
              :formData="formData"
              :tableFields="tableFieldByIdHasId"
              :updateActionType="handleUpdateActionType"
              :updateActionCode="handleUpdateActionCode"
            />

            <template v-if="optionalConfig">
              <IndexConfigForm :formData="formData" />
              <ActionBtnConfigForm :formData="formData" v-if="!isApi" />
              <CacheConfigForm :formData="formData" />
              <CustomizeConfigForm :formData="formData" v-if="!isApi" />
              <ModalConfigForm :formData="formData" v-if="!isApi" />
              <FieldsConfigForm
                :formData="formData"
                :tableFields="tableFieldByFieldHasId"
                :tabFields="tableFieldByIdNoId"
              />
              <ValueSettingForm :formData="formData" />
              <MenuRouteConfigForm :formData="formData" />
            </template>
            <!-- 多语言配置 -->
            <div v-if="menuInfo.lang">
              <MultiLanguageForm
                :formData="formData"
                :languageList="languageList"
                :getTransData="handleGetTransData"
              />
            </div>
          </el-tab-pane>

          <!-- 多表配置选项卡 -->
          <el-tab-pane
            :label="$t('menu.dev.action.tabs.join', '多表关联')"
            name="join"
            v-if="formData.config.has_join || formData.config.has_sql"
          >
            <JoinConfigTab
              :formData="formData"
              :tableFields="tableFieldByFieldHasId"
              :dbConnections="dbConnections"
            />
          </el-tab-pane>
          <!-- 扩展配置选项卡 -->
          <el-tab-pane
            :label="$t('menu.dev.action.tabs.extend', '扩展信息')"
            name="extend"
          >
            <ExtendConfigTab :formData="formData" />
          </el-tab-pane>

          <!-- 配置对象编辑 -->
          <el-tab-pane
            :label="$t('menu.dev.field.tabs.json_edit', '配置编辑')"
            name="json_edit"
          >
            <div class="form-section">
              <ra-object-editor v-model="formData.config" />
            </div>
          </el-tab-pane>
          <!-- 代码编辑器 -->
          <el-tab-pane
            :label="$t('menu.dev.field.tabs.func_edit', '函数编辑')"
            name="func_edit"
            v-if="formData.config.has_customize"
          >
            <div class="form-section">
              <el-input type="textarea" rows="16" v-model="formData.function" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- footer -->
      <template #footer>
        <div>
          <el-button type="info" @click="cancelHandler">
            {{ $t('common.action.cancel', '取消') }}
          </el-button>
          <el-button type="warning" @click="resetHandler">
            {{ $t('common.action.reset', '重置') }}
          </el-button>
          <el-button type="primary" @click="submitHandler" :disabled="loading">
            {{ $t('common.action.confirm', '确定') }}
          </el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup>
// 设置选项式 API 的内容
defineOptions({
  // 组件名称
  name: 'DevActionUpdate',
  // 阻止透传非 props 属性
  inheritAttrs: false,
});

// 引入子组件
import ActionBtnConfigForm from './components/ActionBtnConfigForm.vue';
import BasicInfoForm from './components/BasicInfoForm.vue';
import CacheConfigForm from './components/CacheConfigForm.vue';
import CustomizeConfigForm from './components/CustomizeConfigForm.vue';
import ExtendConfigTab from './components/ExtendConfigTab.vue';
import FieldsConfigForm from './components/FieldsConfigForm.vue';
import IndexConfigForm from './components/IndexConfigForm.vue';
import JoinConfigTab from './components/JoinConfigTab.vue';
import MenuRouteConfigForm from './components/MenuRouteConfigForm.vue';
import ModalConfigForm from './components/ModalConfigForm.vue';
import MultiLanguageForm from './components/MultiLanguageForm.vue';
import ValueSettingForm from './components/ValueSettingForm.vue';

// 引入API
import ActionAPI from '@/api/admin/dev/action';
import MenuAPI from '@/api/admin/dev/menu';
import ApiAPI from '@/api/admin/dev/api';
import LangAPI from '@/api/admin/admin/i18n';

// 引入工具函数
import { clone } from 'xe-utils';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { computed, nextTick } from 'vue';
import { useRoute } from 'vue-router';

// 引入组合函数
import { useFormData } from './composables/useFormData.js';
import { useApiOperations } from './composables/useApiOperations.js';
import { useFormValidation } from './composables/useFormValidation.js';
import { useMultiLanguage } from './composables/useMultiLanguage.js';
import { useModalState } from './composables/useModalState.js';

// 系统的数据库连接
const dbConnections = ref([]);

// 当前菜单的字段列表
// const tableFields = ref([]);

// 当前菜单字段列表（field作为值）
// const tableFieldsByField = ref([]);

// 选项卡字段
// const tabFields = ref([]);

// 当前菜单字段列表（id作为值，包含主键字段）
const tableFieldByIdHasId = ref([]);
// 当前菜单字段列表（id作为值，不包含主键字段）
const tableFieldByIdNoId = ref([]);
// 当前菜单字段列表（field作为值，包含主键字段）
const tableFieldByFieldHasId = ref([]);
// 当前菜单字段列表（field作为值，不包含主键字段）
const tableFieldByFieldNoId = ref([]);

// 字段类型的默认配置
const defaultConfigList = ref({});

// 当前菜单的权限前缀
const permPrefix = ref('');

// 多语言列表
const languageList = ref([]);

// 菜单信息
const menuInfo = ref({});

// Props定义
const props = defineProps({
  mode: {
    type: String,
    default: 'add',
    validator: (value) => ['add', 'update'].includes(value),
  },
});

// 使用组合函数
const {
  formData,
  refForm,
  isLoaded,
  initFormData,
  resetForm,
  updateFormData,
  updateActionType,
  updateActionCode,
} = useFormData();

// 定义可触发事件
const emit = defineEmits(['reload']);

const route = useRoute();
const isApi = computed(() => route.query.app === 'api');

const {
  loading,

  getFormData,
  addData,
  updateData,
  getLanguageKey,
} = useApiOperations(route, ActionAPI, MenuAPI, ApiAPI, LangAPI);

const { formRules, validateForm, clearValidate, resetFields } =
  useFormValidation();

const { getTransData } = useMultiLanguage(LangAPI);

const { show, activeTab, modalTitle, showModal, hideModal, resetActiveTab } =
  useModalState(props);

// 计算属性：是否显示可选配置
const optionalConfig = computed(() => {
  const config = formData.value.config;
  return (
    config.has_btn ||
    config.has_modal ||
    config.has_fields ||
    config.has_cache ||
    config.has_value ||
    config.has_menu ||
    config.has_customize ||
    formData.value.type === 'index' // 直接判断type为index的情况
  );
});

/**
 * 监视
 */
watch(
  () => formData.value.method,
  (newValue, oldValue) => {
    if (newValue || oldValue) {
      try {
        const method = newValue || oldValue;
        handleUpdateActionCode(method);
      } catch (error) {
        console.error('Error generating route details:', error);
      }
    }
  },
);
/**
 * 事件处理函数
 */

// 处理获取翻译数据
const handleGetTransData = async () => {
  await getTransData(formData.value);
};

// 处理更新操作类型
const handleUpdateActionType = (action) => {
  updateActionType(action, defaultConfigList.value);
};

// 处理更新操作代码
const handleUpdateActionCode = async (method) => {
  await updateActionCode(method, permPrefix.value, getLanguageKey);
};

// 提交操作（统一处理新增和编辑）
const submitHandler = async () => {
  try {
    const isValid = await validateForm(refForm.value);
    if (!isValid) return;

    const postData = clone(formData.value);
    console.log('Form Data :', postData);

    if (props.mode === 'add') {
      await addData(formData.value);
    } else {
      console.log('update', formData.value);
      await updateData(formData.value);
    }

    resetForm();
    hideModal();
    resetActiveTab();
    emit('reload');
  } catch (error) {
    console.error(`Error in ${props.mode}Handler:`, error);
  }
};

// 取消操作
const cancelHandler = () => {
  resetForm();
  hideModal();
  resetActiveTab();
};

// 重置表单操作
const resetHandler = () => {
  resetForm();
};

const initModal = () => {
  showModal();
  nextTick(() => {
    clearValidate(refForm.value);
    isLoaded.value = true;
  });
};

/**
 * 暴露方法
 */
defineExpose({
  async show(params) {
    const { id, menu_id, app } = params;
    const { data } = await ActionAPI.initActionForm({ menu_id, app });

    dbConnections.value = data.connection_list || [];

    // 包含ID字段，值为字段id
    // tableFields.value = data.fields.hasId;
    // 包含ID字段，值为字段field
    // tableFieldsByField.value = data.fields.fieldHasId;
    // tabFields.value = data.fields.hasId || []; // hasId noId

    // 包含ID字段的值为id的字段列表
    tableFieldByIdHasId.value = data.fields.hasId;
    tableFieldByIdNoId.value = data.fields.noId;
    tableFieldByFieldHasId.value = data.fields.fieldHasId;
    tableFieldByFieldNoId.value = data.fields.fieldNoId;
    // 方法的默认配置
    defaultConfigList.value = data.action_default || [];
    // 方法的权限前缀
    permPrefix.value = data.permission_prefix || '';
    // 多语言列表
    languageList.value = data.language_list || [];
    // 菜单信息
    menuInfo.value = data.menu_info || {};

    resetForm();
    resetActiveTab();

    if (props.mode === 'add') {
      // 新增模式
      if (menu_id) {
        initFormData();
        updateFormData({ menu_id: menu_id });
      }
      initModal();
    } else {
      // 编辑模式
      try {
        const data = await getFormData(id);
        updateFormData(data);
        initModal();
      } catch (error) {
        console.error('Error loading form data:', error);
        return;
      }
    }
  },
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
